package com.example.demo.mapper;


import com.example.demo.entity.ChapterResource;
import org.apache.ibatis.annotations.*;
import java.util.List;
import java.util.Optional;

@Mapper
public interface ChapterResourceMapper {

    String COLUMNS = "resource_id, chapter_id, resource_type, resource_name, created_at, updated_at";

    // 1. 根据 ID 查找单个资源记录
    @Select("SELECT " + COLUMNS + " FROM chapter_resources WHERE resource_id = #{resourceId}")
    Optional<ChapterResource> findById(@Param("resourceId") Integer resourceId);

    // 2. 根据章节 ID 查找所有资源记录 (利用 idx_chapter_id 索引)
    @Select("SELECT " + COLUMNS + " FROM chapter_resources WHERE chapter_id = #{chapterId} ORDER BY created_at DESC")
    List<ChapterResource> findByChapterId(@Param("chapterId") Integer chapterId);

    // 3. 根据章节 ID 和资源类型查找资源 (利用 idx_chapter_id 和 idx_resource_type 索引)
    @Select("SELECT " + COLUMNS + " FROM chapter_resources WHERE chapter_id = #{chapterId} AND resource_type = #{resourceType} ORDER BY created_at DESC")
    List<ChapterResource> findByChapterIdAndType(@Param("chapterId") Integer chapterId, @Param("resourceType") String resourceType);

    // 4. 插入新的资源记录
    @Insert("INSERT INTO chapter_resources (chapter_id, resource_type, resource_name) " +
            "VALUES (#{chapterId}, #{resourceType}, #{resourceName})")
    @Options(useGeneratedKeys = true, keyProperty = "resourceId")
    int insert(ChapterResource resource);

    // 5. 更新资源信息
    @Update({
            "<script>",
            "UPDATE chapter_resources",
            "SET updated_at = CURRENT_TIMESTAMP()",
            "<if test='resourceType != null'>, resource_type = #{resourceType}</if>",
            "<if test='resourceName != null'>, resource_name = #{resourceName}</if>",
            "WHERE resource_id = #{resourceId}",
            "</script>"
    })
    int update(ChapterResource resource);

    // 6. 根据 ID 删除资源记录
    @Delete("DELETE FROM chapter_resources WHERE resource_id = #{resourceId}")
    int deleteById(@Param("resourceId") Integer resourceId);
}
